package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.execption.PhoneExistExecption;
import com.atguigu.gulimall.member.execption.UsernameExistExecption;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SociaUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;
    /**
     * 分页查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        //设置默认会员等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一
        checkUserUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());

        //密码加密存储  spring提供的密码加密器，自动将密码加盐加密，得到的随机字符串中有盐信息，可以根据盐判断密码是否正确
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他默认信息

        this.baseMapper.insert(entity);
    }

    /**
     * 检查手机号是否唯一
     * @param phone
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistExecption {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count>0){
            throw  new PhoneExistExecption();
        }

    }

    /**
     * 检查用户是否唯一
     * @param username
     */
    @Override
    public void checkUserUnique(String username) throws UsernameExistExecption {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new UsernameExistExecption();
        }

    }

    /**
     * 登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //去数据库中查询
        MemberEntity entity = this.baseMapper.selectOne(
                new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));

        if(entity == null){
            //登录失败
            return null;
        }else{
            //获取到数据库中的密码
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if(matches){
                //匹配成功
                return entity;
            }else{
                //匹配失败
                return null;
            }

        }
    }

    /**
     * 社交登录
     * @param sociaUserVo
     * @return
     */
    @Override
    public MemberEntity login(SociaUserVo sociaUserVo) throws Exception {
        //登录注册合并逻辑
        String uid = sociaUserVo.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity!=null){
            //表明已经注册过了  更新用户信息
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(sociaUserVo.getAccess_token());
            update.setExpiresIn(sociaUserVo.getExpires_in());
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(sociaUserVo.getAccess_token());
            memberEntity.setExpiresIn(sociaUserVo.getExpires_in());
            return memberEntity;
        }else{
            //表明未注册  添加用户
            MemberEntity regist = new MemberEntity();
            try {
                //获取社交用户的社交账号信息（昵称、性别等）
                Map<String, String> query = new HashMap<>();
                query.put("access_token",sociaUserVo.getAccess_token());
                query.put("uid",sociaUserVo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if(response.getStatusLine().getStatusCode() == 200){
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //获取基本信息
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String header = jsonObject.getString("profile_image_url");
    //                ..
                    regist.setNickname(name);
                    regist.setGender(gender.equals("m")?1:0);
                    regist.setHeader(header);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            regist.setAccessToken(sociaUserVo.getAccess_token());
            regist.setExpiresIn(sociaUserVo.getExpires_in());
            regist.setSocialUid(sociaUserVo.getUid());
            this.baseMapper.insert(regist);

            return regist;
        }
    }

}